package com.diabeco.data.measures;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.diabeco.data.DiabecoContract;
import com.diabeco.model.measures.GlycemiaMeasure;
import com.diabeco.model.measures.GlycemiaUnit;

public final class GlycemiaMeasureDaoImpl extends SQLiteOpenHelper implements GlycemiaMeasureDao {

	private Context context;

	private static final String TYPE_TEXT = " TEXT";
	private static final String TYPE_REAL = " REAL";
	private static final String TYPE_INTEGER = " INTEGER";
	private static final String TYPE_DATE = " INTEGER";
	private static final String COMMA_SEP = ",";

	// @formatter:off
	private static final String SQL_CREATE_TABLE_GLYCEMIA_MEASURE = 
			"CREATE TABLE "
			+ DiabecoContract.GlycemiaMeasure.TABLE_NAME
			+ " (" 
			+ DiabecoContract.GlycemiaMeasure._ID + " INTEGER PRIMARY KEY,"
			+ DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_DATE + TYPE_DATE + COMMA_SEP
			+ DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_VALUE + TYPE_REAL + COMMA_SEP
			+ DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_UNIT + TYPE_INTEGER
			+ " )";

	private static final String SQL_DELETE_TABLE_GLYCEMIA_MEASURE = 
			"DROP TABLE IF EXISTS "
			+ DiabecoContract.GlycemiaMeasure.TABLE_NAME;
	// @formatter:on

	private static GlycemiaMeasureDao instance;

	private GlycemiaMeasureDaoImpl(Context context) {
		super(context, DiabecoContract.DATABASE_NAME, null, DiabecoContract.DATABASE_VERSION);
	}

	/**
	 * Retrieves the singleton instance. Receives a context which is used for database initialization but also stored
	 * for subsequent sql operation calls.
	 * 
	 * This method is thread-safe.
	 * 
	 * @return GlycemiaMeasureDao with the instance.
	 */
	public static synchronized GlycemiaMeasureDao getInstance(Context context) {
		if (instance == null) {
			instance = new GlycemiaMeasureDaoImpl(context);
		}

		instance.setContext(context);

		return instance;
	}

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	public void onCreate(SQLiteDatabase db) {
		db.execSQL(SQL_CREATE_TABLE_GLYCEMIA_MEASURE);
	}

	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// This database is only a cache for online data, so its upgrade policy is
		// to simply to discard the data and start over
		db.execSQL(SQL_DELETE_TABLE_GLYCEMIA_MEASURE);
		onCreate(db);
	}

	@Override
	public Long count() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public GlycemiaMeasure select(Long id) {

		GlycemiaMeasure result = null;

		SQLiteDatabase db = GlycemiaMeasureDaoImpl.getInstance(this.getContext()).getReadableDatabase();

		// Define a projection that specifies which columns from the database
		// you will actually use after this query.
		String[] projection = { DiabecoContract.GlycemiaMeasure._ID,
				DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_DATE,
				DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_VALUE,
				DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_UNIT };

		String selection = DiabecoContract.GlycemiaMeasure._ID + " = ?";
		String[] selectionArgs = { id.toString() };

		// How you want the results sorted in the resulting Cursor
		String sortOrder = DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_DATE + " DESC";

		Cursor cursor = db.query(DiabecoContract.GlycemiaMeasure.TABLE_NAME, // The table to query
				projection, // The columns to return
				selection, // The columns for the WHERE clause
				selectionArgs, // The values for the WHERE clause
				null, // don't group the rows
				null, // don't filter by row groups
				sortOrder // The sort order
				);

		cursor.moveToFirst();
		result = this.retrieveGlycemiaMeasureFromCursor(cursor);

		return result;

	}

	@Override
	public List<GlycemiaMeasure> selectBetweenDates(Date from, Date to) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<GlycemiaMeasure> selectAll() {
		List<GlycemiaMeasure> result = new ArrayList<GlycemiaMeasure>();

		SQLiteDatabase db = GlycemiaMeasureDaoImpl.getInstance(this.getContext()).getReadableDatabase();

		// Define a projection that specifies which columns from the database
		// you will actually use after this query.
		String[] projection = { DiabecoContract.GlycemiaMeasure._ID,
				DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_DATE,
				DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_VALUE,
				DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_UNIT };

		String selection = null;
		String[] selectionArgs = null;

		// How you want the results sorted in the resulting Cursor
		String sortOrder = DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_DATE + " DESC";

		Cursor cursor = db.query(DiabecoContract.GlycemiaMeasure.TABLE_NAME, // The table to query
				projection, // The columns to return
				selection, // The columns for the WHERE clause
				selectionArgs, // The values for the WHERE clause
				null, // don't group the rows
				null, // don't filter by row groups
				sortOrder // The sort order
				);

		while (cursor.moveToNext()) {
			GlycemiaMeasure measure = this.retrieveGlycemiaMeasureFromCursor(cursor);
			result.add(measure);
		}

		return result;
	}

	public void persist(GlycemiaMeasure measure) {

		// Gets the data repository in write mode
		SQLiteDatabase db = GlycemiaMeasureDaoImpl.getInstance(this.getContext()).getWritableDatabase();

		// Create a new map of values, where column names are the keys
		ContentValues values = new ContentValues();
		values.put(DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_DATE, measure.getDate());
		values.put(DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_VALUE, measure.getValue());
		values.put(DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_UNIT, measure.getUnit().getValue());

		// Insert the new row, returning the primary key value of the new row
		long newRowId;
		newRowId = db.insert(DiabecoContract.GlycemiaMeasure.TABLE_NAME, null, values);

		System.out.println("Registros grabados en la base de datos: " + newRowId);

	}

	@Override
	public void delete(Long id) {

		// Gets the data repository in write mode
		SQLiteDatabase db = GlycemiaMeasureDaoImpl.getInstance(this.getContext()).getWritableDatabase();

		String removeId = id.toString();

		int rowsDeleted = db.delete(DiabecoContract.GlycemiaMeasure.TABLE_NAME, DiabecoContract.GlycemiaMeasure._ID
				+ "=?", new String[] { removeId });

		if (rowsDeleted != 1) {
			throw new RuntimeException("No se pudo eliminar el registro con id " + id);
		}

	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub

	}

	private GlycemiaMeasure retrieveGlycemiaMeasureFromCursor(Cursor cursor) {
		GlycemiaMeasure measure = new GlycemiaMeasure();

		Long id = cursor.getLong(cursor.getColumnIndexOrThrow(DiabecoContract.GlycemiaMeasure._ID));
		Long date = cursor.getLong(cursor
				.getColumnIndexOrThrow(DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_DATE));
		Float value = cursor.getFloat(cursor
				.getColumnIndexOrThrow(DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_VALUE));
		GlycemiaUnit unit = GlycemiaUnit.getInstance(cursor.getInt(cursor
				.getColumnIndexOrThrow(DiabecoContract.GlycemiaMeasure.COLUMN_NAME_GLYCEMIA_MEASURE_UNIT)));

		measure.setId(id);
		measure.setDate(date);
		measure.setValue(value);
		measure.setUnit(unit);

		System.out.println("Readed glycemia measure: " + measure);

		return measure;
	}

}
